let globalData = getApp().globalData;
import bluetoothTools from "./bluetoothTools.js"
import vm from "@/main.js"
import dataTest from "@/pages/bluetooth/dataTest"
import {
	showModal,
	sleep,
	unique,
	getNowTime
} from './utils.js'
let bluetooth = {
	cardInfo: "",
	iSAllowDcovere: true, //是否允许搜索，防止重复搜索
	//serviceId: "0000FFF0-0000-1000-8000-00805F9B34FB", //服务ID
	serviceId:"8AFAA94E-BDAB-491E-8BCC-48E011BA98B3",
	notifyId: "", //通知ID
	writeId: "", //写卡ID
	sendData: "",
	sendTime: "",
	pageVm:"",
	bluetoothConnect: function() {
		let that = this;
		//初始化蓝牙模块
		uni.openBluetoothAdapter({
			success: function(res) {
				globalData.iSAllowDcovere = true;
				//初始化成功，则开始搜索蓝牙
				that.bluetoothDevicesDiscovery();
			},
			fail: function(res) {
				//提示蓝牙未开启
				uni.$emit('getDiscoveryStatus', false);
				globalData.iSAllowDcovere = true;
				showModal("请开启蓝牙");
			},
			complete: function(res) {
				//监听蓝牙设备器状态
				// let timer = setTimeout(function() {
				//   clearTimeout(timer);
				uni.onBluetoothAdapterStateChange(function(res) {
					if (res.available) {
						// if (!res.discovering) {
						//   if (globalData.iSAllowDcovere) {
						//     Bus.emit('getDiscoveryStatus', true);
						//     that.bluetoothConnect();
						//   }
						// }
					} else {
						//手动关闭了蓝牙
						uni.$emit('getDiscoveryStatus', false);
						globalData.iSAllowDcovere = true;
						that.closeBluetooth();

						//正在写卡,断开蓝牙
						if (globalData.isWriting) {
							showModal("蓝牙已断开,重新点击写卡按钮");
							uni.$emit("isShowLoading", false);
						}
						uni.hideLoading();

						// util.showModal('当前蓝牙不可用,返回首页重新初始化', () => {
						//   util.reLaunch("/pages/windex/windex");
						// });
					}
				})
				// }, 2000);
			}
		})
	},

	//搜索蓝牙
	bluetoothDevicesDiscovery: function() {
		let that = this;
		globalData.iSAllowDcovere = true; //停止搜索，防止再次触发蓝牙设备状态的高边
		uni.startBluetoothDevicesDiscovery({
			services: [],
			success: function(res) {
				console.log("开始搜索蓝牙成功")
				let timer = setTimeout(async function() {
					clearTimeout(timer);
					//5秒钟停止搜索，防止消耗
					await that.stopBluetoothDevicesDiscovery();
				}, 5000)
				that.bluetoothDevicesFound(timer);
			},
			fail: function(res) {

			}
		})
	},

	//过滤掉其他蓝牙设备
	filterDevices: function(devices) {
		// let newArray = devices.filter((item) => {
		//   let name = item.name;
		//   if (name != "") {
		//     let reg = /^BT.*/;
		//     let numReg = /^[0-9]+$/;
		//     if (reg.test(name) || numReg.test(name)) {
		//       return item;
		//     }
		//   }
		// })
		// return newArray;
		return devices;
	},

	//停止搜索蓝牙
	stopBluetoothDevicesDiscovery: function() {
		uni.$emit('getDiscoveryStatus', false);
		return new Promise((resolve, reject) => {
			uni.stopBluetoothDevicesDiscovery({
				success: function(res) {
					resolve();
					console.log("停止蓝牙搜索")
					//显示蓝牙连接失败的提示
					globalData.iSAllowDcovere = false; //停止搜索，防止再次触发蓝牙设备状态的高边
				},
				fail: function(res) {
					console.log(res);
				}
			})
		})
	},
	//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
	//监听寻找到新设备的事件
	bluetoothDevicesFound: function(timer) {
		let that = this;
		//监听寻找到新设备的事件
		uni.onBluetoothDeviceFound(async function(res) {
			console.log("搜索到的蓝牙设备");
			console.log(res.devices);
			let newArray = that.filterDevices(res.devices);
			//ios 会出现已经搜索过的设备
			let bluetoothListArr = [];
			let oldBluetoothListArr = globalData.bluetoothList;
			let oldNameArr = [];
			oldBluetoothListArr.forEach((item) => {
				oldNameArr.push(item.name)
			})
			let flag = false;
			newArray.forEach((newItem) => {
				if (!oldNameArr.includes(newItem.name)) {
					flag = true;
				}
			})

			if (newArray.length > 0 && flag) {
				//搜索到新的蓝牙设备，关闭定时器。并停止搜索
				console.log("搜索到的蓝牙设备")
				clearTimeout(timer);
				//5秒钟停止搜索，防止消耗
				await that.stopBluetoothDevicesDiscovery();
				//过滤到相同的蓝牙设备
				let bluetoothList = [...globalData.bluetoothList, ...newArray];
				let uniQueArr = unique(bluetoothList, "name");
				globalData.bluetoothList = uniQueArr;

				console.log(" globalData.bluetoothList", globalData.bluetoothList)
				uni.$emit('getDevices', globalData.bluetoothList);
			}
		})
	},
	//获取蓝牙适配器状态
	getBluetoothAdapterState() {
		return new Promise((resolve, reject) => {
			uni.getBluetoothAdapterState({
				success: function(res) {
					if (!res.available) {
						showModal('当前蓝牙不可用');
					} else {
						resolve();
					}
				},
				fail: function(res) {
					showModal('当前蓝牙不可用,返回上一页重新初始化', () => {
						navigateTo("/pages/bluetooth/insertCardTip");
					});
				}
			})
		})
	},

	//获取当前已连接的设备
	getConnectedBluetoothDevices: function(callback) {
		let that = this;
		console.log("获取连接的设备")
		uni.getConnectedBluetoothDevices({
			services: [that.serviceId],
			success: function(res) {
				let devices = that.filterDevices(res.devices);
				callback(devices);
			},
			fail: function(res) {
				console.log(res)
				callback([]);
			}
		})
	},

	//连接低功耗蓝牙设备。
	createBLEConnection: function() {
		let that = this;
		uni.createBLEConnection({
			deviceId: globalData.deviceId,
			success: function(res) {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				uni.onBLEConnectionStateChange(function(res) {
					//当前没有连接并且不是首页
					if (!res.connected) {
						//util.devicesUnConnect();
					}
				})
				that.getBLESerciveId();
			},
			fail: function(res) {
				uni.hideLoading();
				showModal(res.errMsg)
				//uni.$emit('isConnect', false);
			}
		})
	},

	//获取蓝牙设备服务ID
	getBLESerciveId: function() {
		let that = this;
		uni.getBLEDeviceServices({
			deviceId: globalData.deviceId,
			success: function(res) {
				let services = res.services;
				console.log("services", services)
				services.forEach(function(item) {
					if (that.serviceId == item.uuid) {
						that.getBLEDeviceCharacteristics()
					}
				})
			},
			fail: function(res) {

			},
			complete: function() {

			}
		})
	},

	//获取蓝牙设备特征值
	getBLEDeviceCharacteristics: function() {
		let that = this;
		uni.getBLEDeviceCharacteristics({
			deviceId: globalData.deviceId,
			serviceId: that.serviceId,
			success: function(res) {
				console.log("deviceId", globalData.deviceId)
				console.log("res", res);
					//that.notifyId = "0000FFF1-0000-1000-8000-00805F9B34FB";
					that.notifyId = "A9BDC753-B202-4CC4-ADD5-A5496B0E64B2";
					that.notifyBLECharacteristicValueChange();
					//that.writeId = "0000FFF2-0000-1000-8000-00805F9B34FB";
			        that.writeId = "A9BDC753-B202-4CC4-ADD5-A5496B0E64B2";
			  
			  //	let characteristics = res.characteristics;
				// characteristics.forEach(function(item) {
				// 	that.notifyId = "0000FFF1-0000-1000-8000-00805F9B34FB";
				// 	that.notifyBLECharacteristicValueChange();
				// 	that.writeId = "0000FFF2-0000-1000-8000-00805F9B34FB";
					
					// if (item.properties.notify) {
					// 	//that.notifyId = item.uuid;
					// 	that.notifyId = "0000FFF1-0000-1000-8000-00805F9B34FB";
					// 	that.notifyBLECharacteristicValueChange();
					// }
					// if (item.properties.write) {
					// 	// that.writeId = item.uuid;
					// 	that.writeId = "0000FFF2-0000-1000-8000-00805F9B34FB";
					// }
				//})
			},
			fail: function(res) {},
			complete: function() {}
		})
	},

	//开启notify通知模式
	notifyBLECharacteristicValueChange: function() {
		let that = this;
		uni.notifyBLECharacteristicValueChange({
			state: true,
			deviceId: globalData.deviceId,
			serviceId: that.serviceId,
			characteristicId: that.notifyId,
			success: function(res) {
				console.log("蓝牙连接成功",res);
				that.onBLECharacteristicValueChange();
				let timer = setTimeout(function() {
					clearTimeout(timer);
					uni.hideLoading();
					console.log("蓝牙连接成功");
					vm.$navigateTo("/pages/bluetooth/dataTest");
					// showModal("蓝牙连接成功,前往写卡页面",function(){
					//  console.log("back")
					//  vm.$navigateBack(2);
					//  // let writePage = getApp().globalData.writePage;
					//  // vm.$navigateTo("/pages/serviceMeter/"+ writePage);
					// })
					//bluetoothTools.onPower();
				}, 1000)
			},
			fail: function(res) {}
		})
	},

	//字符转转化为buffer
	hexStringToArrayBuffer: function(str) {
		return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		})).buffer
	},

	//连续写卡数据
	// writeCard: function(currentComands) {
	//   this.cardInfo = "";
	//   let bufferArray = this.getBufferArray(currentComands);
	//   for (let i = 0; i < bufferArray.length; i++) {
	//     sleep(0.25); //同步延迟0.25ms
	//     this.writeBLECharacteristicValue(bufferArray[i]);
	//   }
	// },

	//
	writeCard: function(currentComands,pageVm) {
		this.pageVm = pageVm;
		this.sendData = currentComands;
		this.cardInfo = "";
		let allBuffer = this.hexStringToArrayBuffer(currentComands);
        sleep(0.25); //同步延迟0.25ms
		this.writeBLECharacteristicValue(allBuffer);
	},

	getBufferArray: function(currentComands) {
		let num = 0;
		console.log("当前读卡命令", currentComands)
		if (typeof currentComands == "undefined") return [];
		let allBuffer = this.hexStringToArrayBuffer(currentComands);
		let bufferLen = allBuffer.byteLength;
		let bufferArray = [];
		while (bufferLen > 0) {
			let buffer;
			if (bufferLen > 20) {
				buffer = allBuffer.slice(num, num + 20);
				num = num + 20;
				bufferLen -= 20;
				bufferArray.push(buffer);
			} else {
				buffer = allBuffer.slice(num, num + bufferLen);
				num += bufferLen;
				bufferLen -= bufferLen;
				bufferArray.push(buffer);
			}
		}
		return bufferArray;
	},

	//分包向蓝牙写入数据
	writeBLECharacteristicValue: function(value) {
		console.log("value", value);
		let that = this;
		that.sendTime = getNowTime();
		uni.writeBLECharacteristicValue({
			deviceId: globalData.deviceId,
			serviceId: that.serviceId,
			characteristicId: that.writeId,
			value,
			success: function(res) {
				console.log(getNowTime() + "======" + that.arrayBufferToHexString(value) + "发送成功");
			},
			fail: function(res) {
				if (res.errCode == '10006') {
					// util.devicesUnConnect();
				} else {
					//showModal(res.errMsg);
				}
			}
		})
	},

	//监听数据的变化
	onBLECharacteristicValueChange: function() {
		let that = this;
		uni.onBLECharacteristicValueChange(function(res) {
			let relust = that.arrayBufferToHexString(res.value);
			console.log(getNowTime() + "======" + relust + "监听成功");
			//that.cardInfo = that.cardInfo + relust;
			that.pageVm[globalData.onValueFunStr].call(that.pageVm,relust);
			
			//    let twoStr = that.cardInfo.substring(0, 2);
			//    let len = parseInt(twoStr, 16) * 2 + 2;
			//    //判断每条指令返回长度 指定长度=cardCommands 长度 如果第一次出现报文指令错误，则重新写入指令
			//    if (that.cardInfo.length == len) {
			//      globalData.returnCommands.push(that.cardInfo);
			//      let returnCommandsLen = globalData.returnCommands.length;
			//      let cardCommandsLen = globalData.cardCommands.length;
			//      if (returnCommandsLen == cardCommandsLen) {
			//       // util.getFunctionByName();
			// console.log("回调"+globalData.onValueFunStr)
			// bluetoothTools[globalData.onValueFunStr](globalData.returnCommands);
			//      } else {
			//        that.writeCard(globalData.cardCommands[++globalData.currentCommandsIndex])
			//      }
			//    }
		})
	},

	//将buffer转化为16进制字符串
	arrayBufferToHexString: function(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('').toUpperCase();
	},

	//关闭蓝牙连接
	closeBLEConnection: function() {
		return new Promise((resolve, reject) => {
			uni.closeBLEConnection({
				deviceId: globalData.deviceId,
				success: function(res) {
					resolve();
				}
			})
		})
	},

	//关闭蓝牙
	closeBluetooth: async function() {
		globalData.iSAllowDcovere = true,
			await this.closeBLEConnection();
		await this.closeBluetoothAdapter();
	},

	//关闭蓝牙模块
	closeBluetoothAdapter: function() {
		return new Promise((resolve, reject) => {
			uni.closeBluetoothAdapter({
				success: function(res) {
					resolve();
				}
			})
		});
	}
}
export default bluetooth;
